package org.nobject.common.regex;

import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.nobject.common.lang.StringUtils;

/**
 * RegexUtils
 * 
 * @author bianrongjun
 * @version 1.0
 */
public class RegexUtils {
	
	/** 
	 * 匹配
	 * @param src
	 * @param regex
	 * @param ignoreCase
	 * @return
	 */
	public static boolean matches(String src,String regex,boolean ignoreCase){
		Pattern p = Pattern.compile(regex,ignoreCase?Pattern.CASE_INSENSITIVE:0);
		Matcher m = p.matcher(src);
        return m.matches();
	}
	
	/** 
	 * 寻找出符合起始标志和结束标志的字串组
	 * 
	 * @param str 字符串源
	 * @param startSign 起始标志
	 * @param endSign 结束标志
	 */
	public static List findPairs(String str,String startSign,String endSign){
		List l=new LinkedList();
		int c=0;
		while((c=str.indexOf(startSign,c+1))>=0){
			int ce=str.indexOf(endSign,c);
			if(ce>0) l.add(str.substring(c,ce)+endSign);
		}
		return l;
	}
	
	/** 
	 * 寻找匹配项,返回List
	 * @param str 字符串
	 * @param regex 正则式
	 */
	public static List findMatches(String str,String regex){
		List<String> l = new LinkedList<String>();
		Matcher m = Pattern.compile(regex).matcher(str);
		while (m.find()) {
			if (!StringUtils.isEmpty(m.group())) l.add(m.group());
		}
		return l;
	}
	
	/** 
	 * 把字符串按照匹配的正则式分组，分组的每个元素是[是否是匹配式,源字符串]
	 * @param str
	 * @param regex
	 */
	public static List divide(String str,String regex){
		List<String> l=findMatches(str,regex);
		List ll	=new LinkedList();
		if(l.size()==0){
			ll.add(new Object[]{false,str});
			return ll;
		}
		
		int last=0;
		for(String s:l){
			int i=str.indexOf(s);
			ll.add(new Object[]{false	,str.substring(last, i)});
			last=i+str.length();
			ll.add(new Object[]{true	,s});
		}
		return ll;
	}
	
	public static void main(String[] args) {
		String s="1、<img src='#_MMVC_PATH_#download/?policy=coreDP&amp;handler=basDfileRead&amp;dfileId=DFILE0000000047' /><pre class=\"aaa\">2222</pre>";
		List l=divide(s, "<pre [^>]*>[^<]*</pre>");
		System.out.println(l.size());
	}
	
	/** partRegx */
	private static String partRegx = "\\w+:[\"'][^\"']*[\"']";
	/** groupRegx */
	public static String groupRegx = "\\{((" + partRegx + ",?)+)\\}";
	
	/**
	 * 转成部分List
	 * 
	 * @param str
	 */
	public static List toParts(String str) {
		return findMatches(str, partRegx);
	}

	/**
	 * 转成组List
	 * 
	 * @param str
	 */
	public static List toGroups(String str) {
		return findMatches(str, groupRegx);
	}
	
	/**
	 * 得到匹配的个数
	 * @param str 字符串
	 * @param regex 正则式
	 */
	public static int getMatchesCount(String str,String regex){
		Matcher m=Pattern.compile(regex).matcher(str);
		int count=0;
		while(m.find()) count++;
		return count;
	}
	
	////////////////////////TODO 下面待检测///////////////////////////
	
	/**
	 * addSlash
	 * @param slashStr       
	 */
	public static String addSlash(String slashStr) {
		return slashStr.replaceAll("\\\\", "\\\\\\\\");
	}

	/**
	 * filterRegxCharOnce
	 * @param source
	 */
	public static String filterRegxCharOnce(String source) {
		source = source 
				.replaceAll("\\<", "\\\\<")
				.replaceAll("\\>", "\\\\>")
				.replaceAll("\\(", "\\\\(")
				.replaceAll("\\)", "\\\\)")
				.replaceAll("\\|", "\\\\|")
				.replaceAll("\\[", "\\\\[")
				.replaceAll("\\]", "\\\\]")
				.replaceAll("\\{", "\\\\\\\\\\\\{")
				.replaceAll("\\}", "\\\\\\\\\\\\}")
				.replaceAll("\\^", "\\\\^")
				.replaceAll("\\*", "\\\\*")
				.replaceAll("\\.", "\\\\.")
				.replaceAll("\\$", "\\\\$")
				.replaceAll("\\+", "\\\\+")
				.replaceAll("\\?", "\\\\?")
				.replaceAll("\n", "\\n")
				.replaceAll("\r", "\\r");
		return source;
	}
	
	/**
	 * filterRegxChar
	 * @param source
	 */
	public static String filterRegxChar(String source) {
		source = source 
				.replaceAll("\\\\", "\\\\\\\\")
				.replaceAll("\\(", "\\\\\\(")
				.replaceAll("\\)", "\\\\\\)")
				.replaceAll("\\|", "\\\\\\|")
				.replaceAll("\\[", "\\\\\\[")
				.replaceAll("\\]", "\\\\\\]")
				.replaceAll("\\{", "\\\\\\{")
				.replaceAll("\\}", "\\\\\\}")
				.replaceAll("\\^", "\\\\\\^")
				.replaceAll("\\*", "\\\\\\*")
				.replaceAll("\\.", "\\\\\\.")
				.replaceAll("\\$", "\\\\\\$")
				.replaceAll("\\+", "\\\\\\+")
				.replaceAll("\\?", "\\\\\\?")
				.replaceAll("\n", "\\\\n")
				.replaceAll("\r", "\\\\r");
		return source;
	}

	/**
	 * filterReplacer
	 * @param source
	 */
	public static String filterReplacer(String source) {
		return source = source.replaceAll("\\$", "\\\\\\$");
	}
	
	/** 
	 * replaceAll
	 * @param source
	 * @param sign
	 * @param replacer
	 */
	public static String replaceAll(String source,String sign,String replacer){
		StringBuffer sbc=new StringBuffer();
		StringBuffer sb=new StringBuffer();
		int c=-1;
		while((c=source.indexOf(sign,c+1))>=0){
			sbc.append(",").append(c);
		}
		if(sbc.length()>0){
			sbc.deleteCharAt(0);
			String[] cs=sbc.toString().split(",");
			int lastc=0;
			for (int i = 0; i < cs.length; i++) {
				int pc=Integer.valueOf(cs[i]);
				sb.append(source.substring(lastc, pc)).append(replacer);
				lastc=pc+sign.length();
			}
			if(lastc<source.length()) sb.append(source.substring(lastc));
		} 
		if(sb.length()==0) return source;
		return sb.toString();
	}
	
	public static void main2(String[] args) {
		System.err.println(replaceAll("abcdef", "a", "ssss"));
		System.out.println("abcdef".indexOf("a",0));
	}
}
